package com.cooba.video_frament;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.cooba.R;
import com.cooba.activitys.VideoDetailsActivity;
import com.cooba.adapter.VideoAdapter;
import com.cooba.bean.BannerBean;
import com.cooba.bean.VideoBeans;
import com.cooba.pullTorefresh.PullToRefreshBase;
import com.cooba.pullTorefresh.PullToRefreshListView;
import com.cooba.utils.CommonUtil;
import com.cooba.utils.ServerURL;
import com.cooba.utils.Utils;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.ta.utdid2.android.utils.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: wangkun
 * @Date : 2016/5/31 13:22
 * @Description :军事
 */
public class MiliTaryFrament extends VideoBaseFragment {
    private View view;
    private static final String DIRNAME="military";
    private static final String TAG="military_video";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        try {
            if (view == null) {
                view = initview(inflater);

            }
            return view;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private View initview(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.base_frament, null, false);
        initPullTorefresh(view);
        initLoadViewHelper(rListView);
        return view;
    }


    private void initPullTorefresh(View view) {
        rListView = (PullToRefreshListView) view.findViewById(R.id.lv_news);
        if (isIncar) {
            rListView.setPullRefreshEnabled(false);
        } else {
            rListView.setPullRefreshEnabled(true);
        }

        rListView.setPullLoadEnabled(true);  //上拉加载，屏蔽
        rListView.setScrollLoadEnabled(true); //设置滚动加载可用
        rListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {//下拉刷新
                getData(DIRNAME, false);
                String stringDate = CommonUtil.getStringDate();
                rListView.setLastUpdatedLabel(stringDate);
            }
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {//上拉加载
                Log.i("wangkun","index: "+index);
                if(index=="null" || StringUtils.isEmpty(index)){
                    Toast.makeText(getContext(), "暂时没有新数据啦", Toast.LENGTH_SHORT).show();
                    new FinishRefresh().execute();
                }
                else if (CommonUtil.isNetWork(getActivity())) {
                    getDataUp(index,DIRNAME, true);
                } else {
                    Toast.makeText(getActivity(), "网络错误", Toast.LENGTH_SHORT).show();
                }
            }
        });

        rListView.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i("wangk","==========>>  "+ position);
                if (banner != null && banner.getBannerList() != null && banner.getBannerList().size() > 0) {
                    position = position - 1;
                }
                String videoUrl = mAdapter.getList().get(position).getVideo_page_url().toString().replaceAll("\\\\", "");
                String videoTitle = Utils.replaceString(mAdapter.getList().get(position).getTitle());
                String videoDs = Utils.replaceString(mAdapter.getList().get(position).getDescription());
                Intent intent = new Intent(getActivity(), VideoDetailsActivity.class);
                intent.putExtra("videoUrl", videoUrl);
                intent.putExtra("videoTitle", videoTitle);
                intent.putExtra("videoDs", videoDs);
                startActivity(intent);

                VideoBeans.VideoListEntity entity=mAdapter.getList().get(position);
                savaVideoHistory(entity);
            }
        });
    }




    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.d("wangkun--", "isVisibleToUser " + isVisibleToUser);
        initIncar();
        if (getUserVisibleHint()) {
            if (banner == null)
                getBanner();
        }
    }

    /**
     * @Author: wangkun
     * @Date : 2016/6/23 13:24
     * @Description :获取顶部广告条
     */
    public void getBanner() {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final String now_time = sDateFormat.format(new java.util.Date());
        httpUtils = new HttpUtils();
        params = new RequestParams();
        params.addBodyParameter("now_time", now_time);
        params.addBodyParameter("tag", TAG);

        httpUtils.send(HttpRequest.HttpMethod.POST, judgeBannerUrl(), params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wang", "获取失败");
                //从缓存中获取
                getData(DIRNAME,false);
            }
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wangkun", "获取成功" + responseInfo.result);
                banner = new Gson().fromJson(responseInfo.result, BannerBean.class);
                if (banner.getBannerList() != null && banner.getBannerList().size() > 0) {
                    initHeadView();
                }else {
                    getData(DIRNAME,false);
                }
            }
        });
    }

    private void initHeadView() {
        rListView.getRefreshableView().addHeaderView(getCustomHeaderView(getContext(), banner.getBannerList()));
        getData(DIRNAME, false);
    }

}